package com.hnqcgczy.service.impl;

import com.hnqcgczy.dao.IShopCartDao;
import com.hnqcgczy.dao.imp.ShopCartDaoImpl;
import com.hnqcgczy.db.MyTransaction;
import com.hnqcgczy.service.IShopCartService;
import com.hnqcgczy.vo.ShopCartVo;
import com.hnqcgczy.vo.TShopcart;

import java.util.List;

public class ShopCartServiceImpl implements IShopCartService {
    @Override
    public int addShopCart(TShopcart cart) {
        MyTransaction myTransaction=new MyTransaction(true);
        IShopCartDao shopCartDao=new ShopCartDaoImpl(myTransaction);
        //定义返回
        int count=-1;
       //新增购物车：如果用户的商品已经存在，修改数量， 否则新增
        TShopcart old=shopCartDao.getShopCartByTuIdAndTpId(cart.getTuId(), cart.getTpId());
        if(old==null){
            //执行新增
            count=shopCartDao.addShopCart(cart);
        }else{
            old.setTsCount(old.getTsCount()+1);
            //执行修改
            count=shopCartDao.updateShopCart(old);
        }
        myTransaction.closeConn();
        return count;
    }

    @Override
    public List<ShopCartVo> getShopCartList(String tuId) {
        //1 事务
        MyTransaction myTransaction=new MyTransaction(true);
        //2 dao
        IShopCartDao sdao=new ShopCartDaoImpl(myTransaction);
        //3 定义返回结果
        List<ShopCartVo> list=sdao.getShopCartList(tuId);
        //4:关闭连接资源
        myTransaction.closeConn();
        //5 返回
        return list;
    }

    @Override
    public int deleteShopCart(int tsId) {
       // 定义事务
        MyTransaction myTransaction=new MyTransaction(true);
        //定义dao
        IShopCartDao sdao=new ShopCartDaoImpl(myTransaction);
        // 调用dao接口
        int count=sdao.delShopCart(tsId);
        // 关闭连接资源
        myTransaction.closeConn();
        //返回结果
        return  count;
    }

    @Override
    public int removeShopCart(String tuId) {
        // 事务
        MyTransaction myTransaction=new MyTransaction(true);
        // 定义dao
        IShopCartDao sdao=new ShopCartDaoImpl(myTransaction);
        //调用dao
        int count =sdao.delShopCartByTuId(tuId);
        // 关闭连接资源
        myTransaction.closeConn();
        //返回结果
        return count;
    }

    @Override
    public int updateShopCart(TShopcart cart) {
        MyTransaction myTransaction=new MyTransaction(true);
        IShopCartDao sdao=new ShopCartDaoImpl(myTransaction);
        int count=sdao.updateShopCart(cart);
        myTransaction.closeConn();
        return count;
    }

    @Override
    public TShopcart getShopCartByTuIdAndTpId(String tuId, long tpId) {
        MyTransaction myTransaction=new MyTransaction(true);
        IShopCartDao shopCartDao=new ShopCartDaoImpl(myTransaction);
        return shopCartDao.getShopCartByTuIdAndTpId(tuId, tpId);
    }
}
